package  
{
  import com.bit101.components.InputText;
  import com.bit101.components.Label;
  import com.bit101.components.ProgressBar;
  import com.bit101.components.PushButton;
  import com.bit101.components.Style;
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.events.FocusEvent;
  import flash.events.KeyboardEvent;
  import flash.ui.Keyboard;
  import mge.StringUtils;
  import mge.Timer;
	/**
   * ...
   * @author ivan
   */
  public class GameBoard extends Sprite
  {
    private const TIME_OUT:Number = 15;
    private const ROUND_TIME:Number = 40;
    
    private var anagramUtil:AnagramUtil;
    
    private var repetitions:Boolean;

    private var wordList:Vector.<String>;
    
    public function GameBoard(roundEndFunction:Function) 
    {
      this.roundEndFunction = roundEndFunction;
      anagramUtil = new AnagramUtil();
      
      textDeleted = false;
      
      for (var i:int = 0; i < 10; i++)
      {
        var l:String = anagramUtil.pickUpRandomLetter();
        availableLetters.push(l);
        originalLetters.push(l);
      }
      
      wordList = repetitions ? anagramUtil.wordsWithLetters(originalLetters) : anagramUtil.wordsWithLettersNoRepetition(originalLetters);
      for (i = 0; i < Math.min(5, wordList.length); i++)
        trace(wordList[i]);
      
      Style.fontSize = 12;
      textField = new InputText(this, 424/2-140, 200, "Escribe aquí tu palabra");
      textField.width = 280;
      textField.addEventListener(FocusEvent.FOCUS_IN, onTextFieldFocus);
      textField.addEventListener(KeyboardEvent.KEY_UP, onTextInput);
      textField.height = 30;
      
      restrict();
      submit = new PushButton(this, 424/2-40, 240, "ACEPTAR", onSubmitPressed);
      submit.height = 30;
      submit.width = 80;
      submit.visible = false;
      
      yourWordPreview = new Label(this, 180, 100, "");
      
      timeLabel = new ProgressBar(this, /*stage.width*/ 424/2-140, 50);
      timeLabel.width = 280;
      timeLabel.maximum = ROUND_TIME;
      
      letterView = new LetterView(availableLetters);
      addChild(letterView);
      
      addEventListener(Event.ENTER_FRAME, onEnterFrame);
      addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }
    
    public function removeAllListeners():void
    {
      textField.removeEventListener(FocusEvent.FOCUS_IN, onTextFieldFocus);
      textField.removeEventListener(KeyboardEvent.KEY_UP, onTextInput);
      removeEventListener(Event.ENTER_FRAME, onEnterFrame);
      removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
      stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
    }
    
    private function onAddedToStage(e:Event):void
    {
      removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
      stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
    }
    
    public function start():void
    {
      timer.start();
    }
    
    private function onKeyDown(e:KeyboardEvent):void
    {
      if (!stage.focus)
      {
        stage.focus = textField.textField;
        // onTextInput(e);
      }
    }
    
    private function onEnterFrame(e:Event):void
    {
      timeLabel.value = (1-timer.getDelta()) * ROUND_TIME;
      if (timer.finished())
      {
        // Round end!
        removeEventListener(Event.ENTER_FRAME, onEnterFrame);
        textField.removeEventListener(FocusEvent.FOCUS_IN, onTextFieldFocus);
        textField.removeEventListener(KeyboardEvent.KEY_UP, onTextInput);
        
        var result:PlayerResult = new PlayerResult();
        result.word = yourWordPreview.text;
        wordList.sort(AnagramUtil.longestFirst);
        result.wordList = wordList;
        result.letters = originalLetters.concat();
        roundEndFunction(result);
      }
    }
    
    private function onSubmitPressed(e:Event):void
    {
      yourWordPreview.text = textField.text;
      yourWordPreview.x = 424 / 2 - yourWordPreview.textField.width / 2;
      textDeleted = false;
      stage.focus = null;
      submit.visible = false;
      textField.text = "";
      letterView.update(textField.text, availableLetters);
      availableLetters = originalLetters.concat();
      restrict();
      textField.text = "Mejora tu palabra mientras haya tiempo";
    }
    
    private function onLetterButtonPressed(e:Event):void
    {
      var letter:String = (e.target as PushButton).label;
      
      // Remove from available list.
      if (!repetitions)
      {
        (e.target as PushButton).enabled = false;
        for (var i:int = 0; i < availableLetters.length; i++)
        if (availableLetters[i] == letter)
        {
          availableLetters.splice(i, 1);
          break;
        }
        restrict();
      }
      
      if (!textDeleted)
      {
        textField.text = "";
        textDeleted = true;
      }
      
      textField.text += letter;
    }
    
    private function onTextInput(e:KeyboardEvent):void
    {
      trace("text input");
      if (e.charCode == Keyboard.ENTER)
      {
        if (submit.visible)
          onSubmitPressed(e);
        return;
      }
      
      submit.visible = anagramUtil.exists(textField.text);
      
      availableLetters = originalLetters.concat();
      
      if (!repetitions)
      {
        letterView.update(textField.text, availableLetters);
      }
      restrict();
    }
        
    private function notInTextfield(item:String, index:int, vector:Vector.<String>):Boolean { return textField.text.indexOf(item) == -1; };
    
    private function restrict():void
    {
      var restrict:String = "";
      for (var i:int = 0; i < availableLetters.length; i++)
        restrict += StringUtils.capitalize(availableLetters[i]);
      textField.textField.restrict = restrict;
    }
    
    
    private var textDeleted:Boolean;
    private function onTextFieldFocus(e:Event):void
    {
      trace("text focus");
      if (!textDeleted)
      {
        trace("deleting text");
        textField.text = "";
        textField.textField.text = "";
        textDeleted = true;
      }
    }
    
    private var originalLetters:Vector.<String> = new Vector.<String>();
    private var availableLetters:Vector.<String> = new Vector.<String>();
    private var textField:InputText;
    private var startButton:PushButton;
    private var submit:PushButton;
    private var yourWordPreview:Label;
    
    private var timeLabel:ProgressBar;
    private var timer:Timer = new Timer(ROUND_TIME * 1000);
    private var roundEndFunction:Function;
    
    private var letterView:LetterView;
    
  }

}